package org.ktm.utils;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;

public class KTMResources extends Resources {

    static private Logger logger = Logger.getLogger(KTMResources.class);

    /**
     * Add support for user-defined exceptions: If default lookup failed via
     * super class, the key apparently corresponds to a user-defined exception:
     * Lookup custom error messages in Bundle.properties resource file located
     * in root directory
     * 
     * @param key
     *            The error key in the resource bundle
     * @param locale
     *            The locale for which the resource is desired
     * @param baseName
     *            The base name of the resource bundle, a fully qualified class
     *            name
     * @param classloader
     *            The class loader from which to load the resource bundle
     * @return The resource string corresponding to key, locale, base name and
     *         class loader
     */
    @Override
    public String getString(String key, Locale locale, String baseName, Class<?> clazz) {
        try {
            return super.getString(key, locale, baseName, clazz);
        } catch (MissingResourceException mre) {
            // This must have been a user-defined exception; perform lookup in
            // Bundle.properties in the root directory
            String result = key;

            try {
                logger.info("User-defined exception: try Bundle.properties in root directory");

                ResourceBundle bundle = Localizer.getResourceBundle(locale, Localizer.RESOURCE_BUNDLE_NAME_DEFAULT);
                if (bundle != null) { return bundle.getString(key); }
            } catch (MissingResourceException mre2) {
                // Just return null string
                logger.info("Bundle.properties in root directory not found...");
            }
            return result;
        }
    }

    public String getString(String key, Object oject, Locale locale) {
        return getString(key, locale, Localizer.RESOURCE_BUNDLE_NAME_DEFAULT, Object.class);
    }
}
